<template>
  <!-- 订单管理 -->
  <div class="order-manage">
    <!-- 标题栏 -->
    <div class="order-title">
      <!-- 标题 -->
      <span class="order-title-text">{{$t('orderManage.title')}}</span>
      <!-- 订单号搜索 -->

      <el-input style="margin-top: 20px;"
                class="search-goods"
                :placeholder="$t('orderManage.orderNum')"
                clearable
                v-model="searchOrder">
        <template slot="append"><span @click="getOrderList">{{$t('common.search')}}</span></template>
      </el-input>
    </div>
    <!-- 搜索栏 -->
    <div class="search-order">
      <!-- 日期 -->
      <!--<span class="search-title">{{$t('orderManage.date')}}</span>-->
      <div class="search">
        <el-date-picker v-model="searchDate"
                        type="daterange"
                        :start-placeholder="$t('orderManage.selectStartDate')"
                        :end-placeholder="$t('orderManage.selectEndDate')"
                        value-format="timestamp"
                        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
      </div>
      <!-- 金额 -->
      <!--<span class="search-title">{{$t('orderManage.amount')}}</span>-->
      <div class="search">
        <el-input class="search-money-input"
                  v-model="minMoney"
                  clearable
                  :placeholder="$t('orderManage.minAmount')"></el-input>
        <span class="sign">-</span>
        <el-input class="search-money-input"
                  v-model="maxMoney"
                  clearable
                  :placeholder="$t('orderManage.maxAmount')"></el-input>
      </div>
      <el-button @click="getOrderList()">{{$t('common.search')}}</el-button>

      <el-row>

        <!--        <el-button type="danger" class="delete"-->
        <!--        @click="keytodelete">一键删除</el-button>-->
      </el-row>
    </div>
    <!-- 订单列表 -->
    <el-table v-loading="loading"
              :data="tableData"
              border>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table :data="props.row.orderdet"
                    style="width: 100%">
            <el-table-column prop="goodsname"
                             :label="$t('reportManage.foodName')"
                             width="380">
            </el-table-column>
            <el-table-column prop="goodscost"
                             width="180"
                             :label="$t('orderManage.unitPrice')">
            </el-table-column>
            <el-table-column prop="goodscount"
                             :label="$t('orderManage.orderNum')"
                             width="180">
            </el-table-column>
            <el-table-column prop="goodsallcost"
                             width="180"
                             :label="$t('orderManage.total')"
                             >
            </el-table-column>
            <el-table-column prop="goods_remark"
                             width="180"
                             :label="$t('orderManage.remarks')"
            >
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="dno"
                       :label="$t('orderManage.orderNum')">
      </el-table-column>
      <el-table-column prop="addtime"
                       :label="$t('orderManage.orderTime')">
        <template slot-scope="scope">
          <span>{{scope.row.addtime*1e3 | formatDateTime}}</span>
        </template>
      </el-table-column>
      <!-- 订单状态 -->
      <!--<el-table-column-->
      <!--prop="is_pay"-->
      <!--:label="$t('orderManage.orderStatus')">-->
      <!--<template scope="scope">-->
      <!--<span :style="{color:scope.row.is_pay==1?'#72bd1e':'#ff2828'}">-->
      <!--{{scope.row.is_pay==1? $t('orderManage.paid') : $t('orderManage.unpaid')}}-->
      <!--</span>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column prop="table_num"
                       :label="$t('orderManage.tablenumber')">
      </el-table-column>
      <el-table-column prop="person_count"
                       :label="$t('orderManage.personNum')">
      </el-table-column>
      <el-table-column prop="adult"
                       :label="$t('orderManage.numberofadults')">
      </el-table-column>
      <el-table-column prop="child"
                       :label="$t('orderManage.numberofchildren')">

      </el-table-column>


      <el-table-column prop="allcost"
                       :label="$t('orderManage.amount')">
        <template slot-scope="scope">
          <span>{{scope.row.allcost | numberFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="content"
                       :label="$t('orderManage.remarks')">

      </el-table-column>

      <el-table-column prop="full_address"
                       :label="$t('orderManage.address')">

      </el-table-column>



      <el-table-column prop="paytype"
                       :label="$t('orderManage.payWay')">

      </el-table-column>

      <el-table-column prop="is_pick"
                       :label="$t('orderManage.getType')">
        <template slot-scope="scope">
          <span>{{scope.row.is_pick ==1?'YES':"NO"}}</span>
        </template>
      </el-table-column>


      <el-table-column fixed="right"
                       align="center"
                       :label="$t('common.operation')">
        <template slot-scope="scope">
          <el-button type="text"
                     size="small"
                     @click="editOrder(scope.row)">{{$t('common.edit')}}</el-button>
          <el-button style="margin-left: 30px;"
                     @click="deleteOrder(scope.row)"
                     type="text"
                     size="small"><span style="color: red">{{$t('common.deleteHandle')}}</span></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px;text-align: center">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="page.num"
                     :page-sizes="page.sizes"
                     :page-size="page.size"
                     :total="page.total"
                     layout="sizes, prev, pager, next">
      </el-pagination>
    </div>
    <el-dialog :title="$t('orderManage.dialogTitle')"
               width="25%"
               :visible.sync="dialogFormVisible">
      <el-form ref="form"
               label-position="top"
               :model="form"
               label-width="196px"
               size="small">
        <el-form-item :label="$t('orderManage.orderTime')">
          <!--<el-input v-model="form.addtime"></el-input>-->
          <el-date-picker v-model="form.timestamp"
                          type="datetime"
                          format="dd-MM-yyyy HH:mm:ss"
                          value-format="timestamp"
                          :placeholder="$t('orderManage.orderTime')">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('orderManage.personNum')">
          <el-input v-model="form.person_count"></el-input>
        </el-form-item>
        <el-form-item :label="$t('orderManage.waiter')">
          <el-select v-model="form.nick_name"
                     :placeholder="$t('orderManage.waiter')">
            <el-option v-for="item in waiterList"
                       :key="item.uid"
                       :label="item.nick_name"
                       :value="item.uid">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('orderManage.remarks')">
          <el-input type="textarea"
                    v-model="form.content"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('common.cancel')}}</el-button>
        <el-button type="primary"
                   @click="saveModifyOrder">{{$t('common.confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
  <!-- /订单管理 -->
</template>

<script>
export default {
  name: 'OrderManage',
  data () {
    return {
      searchDate: '',
      searchOrder: '', //  搜索订单号
      minMoney: '', //  最小金额
      maxMoney: '', //  最大金额
      tableData: [], //  订单列表
      orderStatus: '', //  订单状态
      payWay: '', //  结算方式
      payWayList: [], //  结算方式列表
      waiter: '', //  服务人员
      waiterList: [], //  服务人员列表
      loading: false, //  订单列表加载
      page: {
        num: 1, //  分页页码
        size: 10, //  分页条数
        sizes: [10, 20, 50, 100], //  条数选择
        total: 0 //  总条数
      },
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '120px'
    }
  },

  props: {},

  components: {},

  mounted () {
    // 获取订单列表
    this.getOrderList()
  },

  watch: {},

  computed: {},

  filters: {
    // 时间戳转yyyy-mm-dd-h-m-s格式
    formatDateTime (timeStamp) {
      const date = new Date()
      date.setTime(timeStamp)
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      month = month < 10 ? `0${month}` : month
      let day = date.getDate()
      day = day < 10 ? `0${day}` : day
      let hour = date.getHours()
      hour = hour < 10 ? `0${hour}` : hour
      let minute = date.getMinutes()
      minute = minute < 10 ? ('0' + minute) : minute
      let second = date.getSeconds()
      second = second < 10 ? ('0' + second) : second
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }
  },

  methods: {

    // 一键删除
    keytodelete () {
      
      this.$confirm(`此操作将删除全部订单`, this.$t('common.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel')
      }).then(() => {
        this.$axios.get(`${this.$REQ_URL}shopcenter&action=do_delete&type=1&shopid=${sessionStorage.getItem('shopId')}`
        ).then(res => {
          console.log(res.data)
          if (res.data.state === 200) {
            this.$message({
              type: 'success',
              message: this.$t('common.successDelete')
            })
            this.getOrderList(this.page.num)
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('common.failedDelete')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('common.cancelDelete')
        })
      })

    },
    //  获取订单列表
    getOrderList (pageNum = 1) {
      this.page.num = pageNum
      this.loading = true
      let param = `&shopid=${sessionStorage.getItem('shopId')}&page=${pageNum}&pagesize=${this.page.size}&is_delete=0`
      if (this.searchDate) {
        param += `&start_time=${this.searchDate[0] / 1e3}&end_time=${this.searchDate[1] / 1e3}`
      }
      if (this.maxMoney && this.minMoney) {
        param += `&fmoney=${this.minMoney}&emoney=${this.maxMoney}`
      } else if (this.maxMoney && !this.minMoney) {
        this.$message(this.$t('orderManage.emptyMinAmount'))
        this.loading = false
        return
      } else if (!this.maxMoney && this.minMoney) {
        this.$message(this.$t('orderManage.emptyMaxAmount'))
        this.loading = false
        return
      }
      if (this.orderStatus) {
        param += `&is_pay=${this.orderStatus}`
      }
      if (this.payWay) {
        param += `&pay_way=${this.payWay}`
      }
      if (this.waiter) {
        param += `&uid=${this.waiter}`
      }
      if (this.searchOrder) {
        param += `&dno=${this.searchOrder}`
      }
      this.$axios.get(`${this.$REQ_URL}shopcenter&action=order_list${param}`
      ).then(res => {
        if (res.data.state === 1) {
          this.loading = false
          for (let i = 0; i < res.data.data.order_list.length; i++){
            let item = res.data.data.order_list[i];
            item['full_address'] = item['buyeraddress'] + ' /' + item['area1'] + '/' + item['area2'] + '/' + item['area3'] + ' '+ item['postalcode'] + ' ' + item['city'];
          }

          this.tableData = res.data.data.order_list
          this.page.total = res.data.data.records
        } else if (res.data.state === -1) {
          this.loading = false
          this.tableData = []
          this.page.total = 0
        }
      })
    },

    // 选择每页显示多少条数据
    handleSizeChange (size) {
      this.page.size = size
      this.getOrderList(this.page.num)
    },

    // 选择第几页数据
    handleCurrentChange (page) {
      this.page.num = page
      this.getOrderList(this.page.num)
    },

    // 获取支付方式列表
    getPayWayList () {
      this.$axios.get(`${this.$REQ_URL}app&action=pay_list&shopid=${sessionStorage.getItem('shopId')}`).then(res => {
        if (res.data.state === 1) {
          this.payWayList = res.data.data
        }
      })
    },
    // 获取服务人员列表
    getWaiterList () {
      this.$axios.get(`${this.$REQ_URL}app&action=member_list&shopid=${sessionStorage.getItem('shopId')}`).then(res => {
        if (res.data.state === 1) {
          this.waiterList = res.data.data
        }
      })
    },
    // 删除订单
    deleteOrder (order) {
      this.$confirm(`此操作将删除订单:${order.dno}`, this.$t('common.prompt'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel')
      }).then(() => {
        this.$axios.get(`${this.$REQ_URL}shopcenter&action=do_delete&type=0&orderId=${order.id}&shopid=${sessionStorage.getItem('shopId')}`
        ).then(res => {
          console.log(res.data)
          if (res.data.state === 200) {
            this.$message({
              type: 'success',
              message: this.$t('common.successDelete')
            })
            this.getOrderList(this.page.num)
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('common.failedDelete')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('common.cancelDelete')
        })
      })
    },
    // 编辑订单
    editOrder (item) {
      this.dialogFormVisible = true
      this.form = { ...item }
    },

    // 保存修改订单
    saveModifyOrder () {
      if (!this.form.timestamp) {
        this.$message({
          message: '下单时间不能为空',
          type: 'error'
        })
        return
      }
      this.$axios.get(`${this.$REQ_URL}shopcenter&action=ChangeOrder&orderid=${this.form.id}&uid=${this.form.buyeruid}&addtime=${this.form.timestamp / 1000}&person_count=${this.form.person_count}&content=${this.form.content}`).then(res => {
        if (res.data.state === 200) {
          this.$message({
            message: this.$t('common.successModify'),
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getOrderList()
        }
      }).catch(_ => {
        this.$message({
          message: this.$t('common.failedModify'),
          type: 'error'
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../assets/css/mixin";
.order-manage {
  background: $fc;
  box-shadow: 0 3px 10px 0 rgba(0, 0, 0, 0.1);
  padding: 0 40px 20px;
  margin-bottom: 80px;
  >>> .el-input-group__append,
  .el-input-group__prepend {
    background-color: #ff8214;
    color: #ffffff;
    border: none;
    cursor: pointer;
  }
  .order-title {
    background: $fc;
    height: 80px;
    @include fja();
    border-bottom: 1px solid #dedede;
    .order-title-text {
      text-align: left;
      font-family: PingFang-SC-Semibold;
      font-size: 20px;
      font-weight: bold;
      color: #000000;
      letter-spacing: 0;
    }
    .search-goods {
      width: 300px;
      float: right;
    }
  }
  .search-order {
    display: flex;
    height: 40px;
    line-height: 40px;
    padding: 10px 0;
    margin: 20px auto;
    background: #fafafa;
    border-radius: 6px;
    .search {
      margin-right: 40px;
      .sign {
        color: #dedede;
        padding: 0 10px;
      }
    }
    .el-button {
      background-color: #ff8214;
      border-bottom: 1px solid #ff8214;
      color: #ffffff;
    }
    .search-money-input {
      width: 110px;
    }
  }
}
.delete {
  margin-left: 50px;
}
</style>
